<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Session;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Models\AdvModel;
use App\Http\Models\ArticleModel;
use App\Http\Models\ExpressModel;
class AdvController extends Controller
{

    public function index()
    {

        $data['data'] = AdvModel::paginate(10);
        $data['type']=3 ;
        return view('adv.index',compact('data'));
    }
    public function add(Request $request)
    {
        if ($request->isMethod('get')){
             $article=ArticleModel::paginate(10);
            return view('adv.add',compact('article'));
        }else{

            $data = $request->except(['_token','uploadfile']);
            $validator = Validator::make($data, [
                'article_id'     => 'required|integer',
                'image' => 'required|mimes:png,gif,jpeg,jpg,bmp'
            ]);
            if ($validator->fails()) {
                return redirect('/adv/add')
                    ->withErrors($validator)
                    ->withInput($data);
            };
            $path = public_path('admin/adv');
            $image_path='/admin/adv/';
            $res = fileUpload($request, 'image', $path, ['jpg', 'jpeg', 'png']);

            $data['image']=str_replace_ds($image_path.$res['msg'][1]);

            $res=AdvModel::create($data);
            $data['data'] = AdvModel::paginate(10);
            $data['type']=3 ;
            return redirect('/adv/index');
        }
    }



    public function edit($id)
    {
        //
    }

    public function update(Request $request, $id)
    {
        //
    }

    public function del(Request $request)
    {

        $id = $request->input('id');
        $result = AdvModel::where(['id'=>$id])->first();
        if(!empty($result)) {
            $data= explode('/',$result->image);
            $url=$data[3].'/'.$data[4];
            $url=public_path($url).'/'.$data[5] ;
            if(empty($result->image)){
                unlink(str_replace_dsstring($url));
            }
            AdvModel::where(['id'=>$id])->delete();
            return response()->json(['status' => 200, 'msg' =>'删除成功']);
        }
        return response()->json(['status' => 500, 'msg' =>'删除失败']);
    }

    public function stage_info(){
       $data= ExpressModel::all();
       return $data ;
    }



}
